package com.gaeainfo.modules.auth.controller;

import com.gaeainfo.constant.GaeaConstant;
import com.gaeainfo.framework.core.basic.GaeaResourceProxy;
import com.gaeainfo.framework.core.basic.dto.BaseResponseDto;
import com.gaeainfo.framework.core.utils.common.GaeaCommonUtil;
import com.gaeainfo.modules.base.dto.PoliceDto;
import com.gisinfo.auth.webapp.webservice.client.AuthServiceClient;
import com.gisinfo.auth.webapp.webservice.client.WSDepartment;
import com.gisinfo.auth.webapp.webservice.client.WSPermissionResult;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Caven on 2018/3/5.
 */
@Controller
@RequestMapping("auth")
public class AuthController {

    private Logger logger = Logger.getLogger(getClass());

    @ResponseBody
    @RequestMapping(value = "sign-in")
    public BaseResponseDto signIn(@RequestParam("username") String username, @RequestParam("password") String password) {
        try {
            AuthServiceClient client = new AuthServiceClient(GaeaResourceProxy.getInstance().getStringByKey("auth.web.ws.url", "system"));
            WSPermissionResult authResult = client.doGetPermissionWithAuth(username, password, "");
            PoliceDto policeDto = new PoliceDto();
            if (authResult.isSuccess()) {
                policeDto.setPoliceNo(authResult.getUser().getLoginName());
                policeDto.setPoliceName(authResult.getUser().getRealName());
                policeDto.setPhone(authResult.getUser().getExtNumber());
                WSDepartment[] deptList = authResult.getDepartment();
                if (!GaeaCommonUtil.isNullOrEmpty(deptList)) {
                    policeDto.setDeptId(deptList[0].getCode());
                    policeDto.setDeptName(deptList[0].getName());
                }

                //设置用户级别，根据不同的业务设置
                if (GaeaCommonUtil.isNullOrEmpty(policeDto.getDeptId())) {
                    policeDto.setUserLevel(GaeaConstant.UserLevel.LEVEL_ADMIN);
                } else {
                    if ("00000000".equals(policeDto.getDeptId().substring(4))) {
                        policeDto.setUserLevel(GaeaConstant.UserLevel.LEVEL_CITY_BUREAU);
                    } else if ("000000".equals(policeDto.getDeptId().substring(6))) {
                        policeDto.setUserLevel(GaeaConstant.UserLevel.LEVEL_SUB_BUREAU);
                    } else if ("0000".equals(policeDto.getDeptId().substring(8))) {
                        policeDto.setUserLevel(GaeaConstant.UserLevel.LEVEL_POLICE_STATION);
                    }
                }
            }
            return BaseResponseDto.successtData(policeDto);
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
            return BaseResponseDto.exception(e);
        }
    }


}
